//
//  MGRouter.m
//  Express
//
//  Created by lhongl on 2025/9/28.
//  Copyright © 2025 QM. All rights reserved.
//

#import "MGRouter.h"
#import "MGNavigator.h"
#import "UIViewController+Router.h"
#import "MGJRouter.h"
#import "MGEmpty.h"
@implementation MGRouter

+ (instancetype)sharedInstance{
    static MGRouter *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[MGRouter alloc] init];
    });
    return _instance;
}

#pragma mark - 添加路由
+ (void)addRouter:(NSString *)router forViewController:(Class)cls {
    NSAssert(router, @"[MG_DEBUG] router不能为空");
    NSAssert([cls isSubclassOfClass:[UIViewController class]], @"[MG_DEBUG] cls必须是UIViewController子类");

    [MGJRouter registerURLPattern:router toObjectHandler:^id(NSDictionary *routerParameters) {
#ifdef DEBUG
        NSLog(@"[MG_DEBUG] routerParameters:%@",routerParameters);
#endif
        id object = [cls new];
        [routerParameters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if (!([key isEqualToString:MGJRouterParameterURL]||[key isEqualToString:MGJRouterParameterUserInfo]||[key isEqualToString:MGJRouterParameterCompletion])) {
                //KVC
                [object setValue:obj forKey:key failure:^(NSString *key) {
                    if ([[MGRouter sharedInstance].delegate respondsToSelector: @selector(unFoundParamaterForKey:)]) {
                        [[MGRouter sharedInstance].delegate unFoundParamaterForKey:key];
                    }
                }];
            }
        }];
        NSDictionary *userInfo = routerParameters[MGJRouterParameterUserInfo];
        [userInfo enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            //KVC
            [object setValue:obj forKey:key failure:^(NSString *key) {
                if ([[MGRouter sharedInstance].delegate respondsToSelector: @selector(unFoundParamaterForKey:)]) {
                    [[MGRouter sharedInstance].delegate unFoundParamaterForKey:key];
                }
            }];
        }];
        return object;
    }];
}

#pragma mark 获取viewcontroller
+ (UIViewController *)viewControllerForURL:(NSString *)url userInfo:(NSDictionary *)userInfo {
    if (!url || url == nil || url.length == 0) {
        return nil;
    }
    if (userInfo) {
        return [MGJRouter objectForURL:url withUserInfo:userInfo];
    } else {
        return [MGJRouter objectForURL:url];
    }
}

#pragma mark 打开url
+ (void)openURL:(NSString *)url {
    [self openURL:url userInfo:nil failure:nil];
}

#pragma mark 打开url
+ (void)openURL:(NSString *)url userInfo:(NSDictionary<NSString *,id> *)userInfo {
    [self openURL:url userInfo:userInfo failure:nil];
}

#pragma mark 打开url
+ (void)openURL:(NSString *)url failure:(void (^ _Nullable)(NSString * _Nonnull))failBlock {
    [self openURL:url userInfo:nil failure:failBlock];
}

#pragma mark 打开url
+ (void)openURL:(NSString *)url userInfo:(NSDictionary<NSString *,id> *)userInfo failure:(void (^ _Nullable)(NSString * _Nonnull))failBlock {
    if ([[MGRouter sharedInstance].delegate respondsToSelector:@selector(rewriteURL:)]) {
        url = [[MGRouter sharedInstance].delegate rewriteURL:url];
    }
    UIViewController *viewController = [self viewControllerForURL:url userInfo:userInfo];
    if (!viewController) {
        if ([[MGRouter sharedInstance].delegate respondsToSelector:@selector(unFoundRouterForURL:)]) {
            [[MGRouter sharedInstance].delegate unFoundRouterForURL:url];
        };
        if (failBlock) {
            failBlock(url);
        }
    } else {
        [MGNavigator pushViewController:viewController];
    }
}

#pragma mark 返回
+ (void)goback:(BOOL)animated {
    [MGNavigator goback:animated];
}

#pragma mark 返回
+ (void)gobackToURL:(NSString *)url {
    [self gobackToURL:url userInfo:nil];
}

+ (void)gobackToURL:(NSString *)url userInfo:( NSDictionary <NSString *,id> * _Nullable )userInfo {
    UIViewController *viewController = [MGNavigator currentViewController];
    if (viewController.navigationController) {
        UINavigationController *nav = viewController.navigationController;
        UIViewController *viewController = [self viewControllerForURL:url userInfo:nil];
        UIViewController *targetVC = nil;
        for (UIViewController *vc in [nav viewControllers]) {
            if ([vc isKindOfClass:[viewController class]]) {
                targetVC = vc;
            }
        }
        if (!targetVC) {
#ifdef DEBUG
            NSLog(@"[MG_DEBUG] goback failed");
#endif
            return;
        }
        if (!MGEmpty.isEmptyDiction(userInfo)) { /// 不为空
            [userInfo enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                //KVC
                [targetVC setValue:obj forKey:key failure:^(NSString *key) {
                    if ([[MGRouter sharedInstance].delegate respondsToSelector: @selector(unFoundParamaterForKey:)]) {
                        [[MGRouter sharedInstance].delegate unFoundParamaterForKey:key];
                    }
                }];
            }];
        }
        [nav popToViewController:targetVC animated:YES];
    } else {
#ifdef DEBUG
        NSLog(@"[MG_DEBUG] goback failed");
#endif
    }
}

@end
